package asia.yuanding.wechat.web.netty.handler;

import asia.yuanding.wechat.system.util.JwtUtil;
import asia.yuanding.wechat.system.util.RedisUtil;
import asia.yuanding.wechat.web.netty.manager.ChannelManager;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Collections;

/**
 * @ClassName: HttpRequestHandler
 * @Author: YuanDing
 * @Date: 2025/8/3 21:07
 * @Description:
 */

@Component
@ChannelHandler.Sharable
public class HttpRequestHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest req = (FullHttpRequest) msg;

            URI uri = new URI(req.uri());
            QueryStringDecoder decoder = new QueryStringDecoder(uri);

            String token = decoder.parameters().getOrDefault("token", Collections.singletonList("")).get(0);

            // token为空或不合法无法注册 || redisUtil.get(jwtUtil.getUId(token)) == null
            if (StrUtil.isBlankIfStr(token) || !jwtUtil.verifyToken(token)) {
                // 返回 401 响应并关闭连接
                ctx.writeAndFlush("认证失败").addListener(ChannelFutureListener.CLOSE);
                return; // 这里直接 return，不再往下传递
            }

            String uId = jwtUtil.getUId(token);

            ChannelManager.addUser(uId , ctx.channel());

            ctx.channel().attr(AttributeKey.valueOf("uId")).set(uId);

            ctx.fireChannelRead(msg); // 继续传递，不需要 retain()
        } else {
            super.channelRead(ctx, msg);
        }
    }
}



